﻿#if SILVERLIGHT
using System.Windows;
using System.Threading.Tasks;
#elif NETFX_CORE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
#elif WPF
using System.Threading.Tasks;
using System.Windows;
#endif

namespace Xyzzer.AsyncUI
{
    public static class FrameworkElementExtensions
    {
        /// <summary>
        /// Waits for the element to load (construct and add to the main object tree).
        /// </summary>
        public static async Task WaitForLoadedAsync(this FrameworkElement frameworkElement)
        {
            await EventAsync.FromRoutedEvent(
                eh => frameworkElement.Loaded += eh,
                eh => frameworkElement.Loaded -= eh);
        }

        /// <summary>
        /// Waits for the element to unload (disconnect from the main object tree).
        /// </summary>
        public static async Task WaitForUnloadedAsync(this FrameworkElement frameworkElement)
        {
            await EventAsync.FromRoutedEvent(
                eh => frameworkElement.Unloaded += eh,
                eh => frameworkElement.Unloaded -= eh);
        }

        public static async Task WaitForLayoutUpdateAsync(this FrameworkElement frameworkElement)
        {
            await EventAsync.FromEvent<object>(
                eh => frameworkElement.LayoutUpdated += eh,
                eh => frameworkElement.LayoutUpdated -= eh);
        }
    }
}
